package com.bristua.common.config;


import com.bristua.common.bean.Result;
import com.bristua.common.enums.CommonCode;
import com.bristua.common.exception.BizException;
import com.bristua.common.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result otherExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        Result result = new Result();
        result.setCode(CommonCode.SYS_EXCEPTION.getCode());
        result.setMsg(CommonCode.SYS_EXCEPTION.getMsg());
        logger.error("==>其他异常:"+e.getMessage(),e);
        return result;
    }
    
    @ExceptionHandler(value = {BizException.class, SystemException.class})
    @ResponseBody
    public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
        Result result = new Result();
        if(e instanceof BizException){
            BizException biz =(BizException)e;
            result.setMsg(biz.getMessage());
            result.setCode(biz.getCode());
            logger.error("==>业务错误代码:{},错误消息:{}",biz.getCode(),biz.getMessage());
        }
        if(e instanceof SystemException){
            SystemException systemException =(SystemException)e;
            result.setMsg(systemException.getMessage());
            result.setCode(systemException.getCode());
            logger.error("==>程序错误代码:{},错误消息:{}",systemException.getCode(),systemException.getMessage());
        }
        return result;
    }
    
}

